"use client";

import { Loader2 } from "lucide-react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useMemo } from "react";

import { useStore, retrieveMessages } from "~/core/store";
import { useAgentCode } from "~/hooks/use-agent-code";
import { cn } from "~/lib/utils";

import { MessagesBlock } from "./components/messages-block";
import { ResearchBlock } from "./components/research-block";

export default function Main() {
  const pathname = usePathname();
  const router = useRouter();
  const searchParams = useSearchParams();
  const paramThreadId = searchParams.get("threadId");

  const openResearchId = useStore((state) => state.openResearchId);
  const storeThreadId = useStore((state) => state.threadId);
  const loading = useStore((state) => state.loading);
  const agentCode = useAgentCode();

  useEffect(() => {
    if (paramThreadId) {
      if (paramThreadId !== storeThreadId && !loading) {
        void retrieveMessages(agentCode, paramThreadId);
      }
    } else {
      const params = new URLSearchParams(searchParams.toString());
      params.set("threadId", storeThreadId);
      router.push(`${pathname}?${params.toString()}`);
    }
  }, [
    agentCode,
    storeThreadId,
    paramThreadId,
    loading,
    pathname,
    router,
    searchParams,
  ]);

  const doubleColumnMode = useMemo(
    () => openResearchId !== null,
    [openResearchId],
  );

  return (
    <div className="flex h-full w-full flex-row gap-4">
      <MessagesBlock
        className={cn(
          "mx-auto w-full transition-all duration-300 ease-out",
          !doubleColumnMode && "mx-auto w-full max-w-3xl",
          doubleColumnMode && "flex-2",
          loading && "hidden",
        )}
      />
      {doubleColumnMode && (
        <ResearchBlock
          className="min-w-0 flex-3 transition-all duration-300 ease-out"
          researchId={openResearchId}
        />
      )}
      {loading && (
        <div className="absolute top-0 right-0 bottom-0 left-0 z-10 flex items-center justify-center bg-black/50">
          <Loader2 className="text-primary h-8 w-8 animate-spin" />
        </div>
      )}
    </div>
  );
}
